<?php

namespace App\Models;

use App\Common\Func;
use App\Scopes\DeleteScope;
use App\Scopes\TenantScope;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Session;

class BaseModel extends Model
{
    use ModelTrait;

    protected $dates = ['create_time', 'update_time'];

    protected $casts = [
        'create_time' => 'datetime',
        'update_time'
    ];

    const CREATED_AT = 'create_time';

    const UPDATED_AT = 'update_time';

    protected static function booted()
    {
        static::addGlobalScope(new TenantScope());
        static::addGlobalScope(new DeleteScope());
    }

    /**
     * 过滤字段
     * @param array $data 待过滤数组
     * @param array $fields 过滤规则
     * @return array
     */
    public static function filterFields($data, $fields)
    {
        return array_intersect_key($data, array_flip($fields));
    }

    /**
     * 格式化时间
     * @param \DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public static function setTenantId($params): array
    {
        $params['tenant_id'] = $params['tenantId'] ?? Session::get('tenantId');
        return $params;
    }

    public static function setAppPackageId($params): array
    {
        $params['app_package_id'] = $params['appPackageId'] ?? Session::get('appPackageId');
        return $params;
    }
}
